<?php

namespace app\home\controller;

use think\Controller;
use app\common\model\Cart as Carts;


class Cart extends Base
{



public function index(){
    
        if(request()->isGet()){
            //如果get请求
            $this->redirect('home/index/index');

        }
        $params=input();
        // dump($params);
         $data=$this::addCart($params['goods_id'],$params['number']);
          $user_id=session('user_info.id');
          $goods=\app\home\model\Goods::alias('t1')->join('Cart t2','t1.`id`=t2.`goods_id`','left')
->field('t1.*,t2.id,t2.user_id,t2.number,t2.is_selected')->where('t2.user_id',$user_id)->select();
          $number=0;
          
          foreach($goods as $v){
           $number+=$v['goods_price']*$v['number'];
          }
//  dump($params['number']);


$goods=\app\home\model\Goods::alias('t1')->join('Cart t2','t1.`id`=t2.`goods_id`','left')
->field('t1.*,t2.id,t2.user_id,t2.number,t2.is_selected')->where('t2.user_id',$user_id)->select();
// dump($goods);
return $this->fetch('index',['goods'=>$goods,'number'=>$number]);
}

public static function addCart($goods_id,$number,$is_selected=1){

    if(session('user_info')){
        $user_id=session('user_info.id');
        $where=[
            'user_id'=>$user_id,
            'goods_id'=>$goods_id,
            'number'=>$number,
            


        ];
        $info=Carts::where($where)->find();
        if($info){
            $info->number=$number;
            $info->is_selected=$is_selected;
            $info->save();
        }else{
            $where['user_id']=$user_id;
            $where['number']=$number;
            $where['is_selected']=$is_selected;
            $params=Carts::create($where);
        }


    }
}
//登录和没登陆
public function shop(){
    
    if(session('user_info')){
        $user_id=session('user_info.id');
        $goods=\app\home\model\Goods::alias('t1')->join('Cart t2','t1.`id`=t2.`goods_id`','left')
->field('t1.*,t2.id,t2.user_id,t2.number,t2.is_selected')->where('t2.user_id',$user_id)->select();
   $number=0;
   foreach($goods as $v){
    $number+=$v['goods_price']*$v['number'];
   }
return $this->fetch('index',['goods'=>$goods,'number'=>$number]);


    }else{
        $user_id=session('user_info.id');
        $goods=\app\home\model\Goods::alias('t1')->join('Cart t2','t1.`id`=t2.`goods_id`','left')
->field('t1.*,t2.id,t2.user_id,t2.number,t2.is_selected')->where('t2.user_id',$user_id)->select();
        $number=0;
        foreach($goods as $v){
         $number+=$v['goods_price']*$v['number'];
        }
        $user_id=session('user_info.id');
        $goods=Carts::where('user_id',$user_id)->select();
        return $this->fetch('index',['goods'=>$goods,'number'=>$number]);
    }
}

public function delect($id){
    Carts::where('id',$id)->delete();
    $this->redirect('home/cart/shop');
}
}
